package com.codetile.batch.db;

import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStreamWriter;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.database.JdbcPagingItemReader;
import org.springframework.batch.item.database.Order;
import org.springframework.batch.item.database.support.MySqlPagingQueryProvider;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.support.ClassifierCompositeItemWriter;
import org.springframework.batch.item.support.CompositeItemProcessor;
import org.springframework.batch.item.xml.StaxEventItemWriter;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@EnableBatchProcessing
public class ItemReaderDbDemo {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private DataSource dataSource;

    @Autowired
    @Qualifier("dbJdbcWrite")
    private ItemWriter<? super User> dbWrite;


    @Autowired
    @Qualifier("multiFile1ItemWriter")
    private ItemWriter<User> multiFileItemWriter;

    @Autowired
    @Qualifier("xml1Writer")
    private ItemStreamWriter xmlItemWriter;

    @Autowired
    @Qualifier("fileItem1Writer")
    private ItemStreamWriter fileItem1Writer;

    @Autowired
    @Qualifier("myProcessor")
    private ItemProcessor myProcessor;


    @Bean
    public Job dbJob(){
        return jobBuilderFactory.get("dbJob")
                .start(dbStep1())
                .build();
    }

    @Bean
    public Step dbStep1(){
        return stepBuilderFactory.get("splitStep1")
                .<User,User>chunk(2)
                .reader(dbRead())
//                .writer(dbWrite)
                .processor(myProcessor)
                .writer(multiFileItemWriter)
                .stream(fileItem1Writer)
                .stream(xmlItemWriter)

                .build();

    }

    /**
     * 错误处理
     * @return
     */
    @Bean
    @StepScope
    public Tasklet tasklet1(){
        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                Map<String,Object> map=chunkContext.getStepContext().getStepExecutionContext();
                if(map.containsKey("aaaa")){
                    System.out.println("will run sucesss");
                    return RepeatStatus.FINISHED;
                }else {
                    System.out.println("will fail");
                    chunkContext.getStepContext().getStepExecution().getExecutionContext().put("aaaa",true);
                    throw new RuntimeException("error....");
                }

            }
        };
    }



    @Bean
    @StepScope
    public JdbcPagingItemReader<User> dbRead(){
        JdbcPagingItemReader<User> reader=new JdbcPagingItemReader<>();
        reader.setDataSource(dataSource);
        reader.setFetchSize(2);
        reader.setRowMapper(new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user=new User();
                user.setId(resultSet.getInt(1));
                user.setName(resultSet.getString(2));
                user.setAge(resultSet.getInt(3));

                return user;
            }
        });

        MySqlPagingQueryProvider provider=new MySqlPagingQueryProvider();
        //指定查询字段
        provider.setSelectClause("id,name,age");
        //指定查询表
        provider.setFromClause("from user");
        //指定排序字段
        Map<String, Order> sort=new HashMap<>(1);
        sort.put("id", Order.ASCENDING);
        provider.setSortKeys(sort);
        reader.setQueryProvider(provider);
        return reader;
    }


    /**
     * 多种处理方式
     * @return
     */
    @Bean
    public CompositeItemProcessor<User,User> processor(){
        CompositeItemProcessor<User,User> processor=new CompositeItemProcessor();
        List<ItemProcessor<User,User>> list=new ArrayList<>();
        list.add(myProcessor);
//        list.add(...);
        return processor;
    }


}
